import cgi
import wsgiref.handlers
import os

import string
from random import Random

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db

class Prefs(db.Model):
  owner = db.UserProperty()
  prefs = db.StringProperty(multiline=True)
  apiKey = db.StringProperty()

class PrefsPage(webapp.RequestHandler):
  def get(self):
    if users.get_current_user():
      prefsQuery = Prefs.all()
      prefsQuery.filter('owner =', users.get_current_user())
      prefsResults = prefsQuery.fetch(1)
      if (len(prefsResults) != 1):
        self.response.set_status(404, 'No preferences found')
      else:
        for prefs in prefsResults:
          self.response.out.write(prefs.prefs)
    else:
      self.response.set_status(401, 'You must be logged in to edit your preferences')

  def post(self):
    if users.get_current_user():
      prefsQuery = Prefs.all()
      prefsQuery.filter('owner =', users.get_current_user())
      prefsResults = prefsQuery.fetch(1)
      if (len(prefsResults) != 1):
        prefs = Prefs()
        prefs.owner = users.get_current_user()
      else:
        for prefsIterator in prefsResults:
          prefs = prefsIterator
      prefs.prefs = self.request.body
      prefs.put()
      self.response.out.write(prefs.prefs)
    else:
      self.response.set_status(401, 'You must be logged in to edit your preferences')

class ApiKey(webapp.RequestHandler):

  def get(self):
    if users.get_current_user():
      prefsQuery = Prefs.all()
      prefsQuery.filter('owner =', users.get_current_user())
      prefsResults = prefsQuery.fetch(1)
      if (len(prefsResults) != 1):
        self.response.set_status(404, 'No key found')
      else:
        for prefs in prefsResults:
          self.response.out.write(prefs.apiKey)
    else:
      self.response.set_status(401, 'You must be logged in to edit your preferences')

  def post(self):
    if users.get_current_user():
      prefsQuery = Prefs.all()
      prefsQuery.filter('owner =', users.get_current_user())
      prefsResults = prefsQuery.fetch(1)
      if (len(prefsResults) != 1):
        prefs = Prefs()
        prefs.owner = users.get_current_user()
      else:
        for prefsIterator in prefsResults:
          prefs = prefsIterator
      if self.request.body == "1":
        prefs.apiKey = ''.join( Random().sample(string.letters+string.digits, 20) )
      else:
        prefs.apiKey = "0"
      prefs.put()
      self.response.out.write(prefs.apiKey)
    else:
      self.response.set_status(401, 'You must be logged in to edit your preferences')

def main():
  application = webapp.WSGIApplication(
      [
        ('/prefs/key', ApiKey),
        ('/prefs.*', PrefsPage)
      ],
      debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
